<?php
namespace App\Http\Logic;


use App\Http\Service\CategoryService;
use App\Models\Card;
use Illuminate\Support\Facades\DB;

class CardLogic extends BaseLogic
{
	public function __construct()
	{
		parent::__construct();
	}

	public function store($request)
    {
        // 查看分类是否是本人的
        if (!$category = CategoryService::service()->getOneByIdUserId($request['category_id'], $this->user->id)) {
            $this->throwNewInvalidException('不被允许的操作', 422);
        }

        // 如果有图片 查看图片是否存在
        if (!empty($request['image_url'])) {
            $disk = \Storage::disk('qiniu');
            if (!$disk->has($request['image_url'])) {
                $this->throwNewInvalidException('图片不存在,请重新上传...', 422);
            }

            // 把文件从tmp/文件夹下移出来
            $newPath = \Str::after($request['image_url'] , 'tmp/');
            $disk->move($request['image_url'], $newPath);
        }

        DB::beginTransaction();
        try {
            // 1.新增卡片
            $request['image_url'] = $newPath ?? '';
            $card = Card::create($request);
            // 2.增加分类中 卡片数量和待复习数量
            $category->increment('card_num',1,['wait_card_num' => DB::raw('`wait_card_num` + 1')]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e->getLine() . '-' . $e->getMessage());
        }

        return $card->toArray();
    }
}
